#include "labelnamelistmodel.h"

LabelNameListModel::LabelNameListModel(QObject *parent)
    : QAbstractListModel(parent)
{}

int LabelNameListModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) return 0;
    return myLabelNames.size();
}

QVariant LabelNameListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= myLabelNames.size()) return QVariant();

    if (role == Qt::DisplayRole) {
        return myLabelNames[index.row()];
    }

    return QVariant();
}

void LabelNameListModel::tryAddName(const QString &name)
{
    if (name.isEmpty()) return;

    if (!myNameCounts.contains(name)) {
        beginInsertRows(QModelIndex(), myLabelNames.size(), myLabelNames.size());
        myLabelNames.append(name);
        endInsertRows();
    }

    myNameCounts[name]++;
}

void LabelNameListModel::tryRemoveName(const QString &name)
{
    if (!myNameCounts.contains(name)) return;

    myNameCounts[name]--;
    // if (myNameCounts[name] <= 0) {
    //     int index = myLabelNames.indexOf(name);
    //     if (index != -1) {
    //         beginRemoveRows(QModelIndex(), index, index);
    //         myLabelNames.removeAt(index);
    //         endRemoveRows();
    //     }
    //     myNameCounts.remove(name);
    // }
}

void LabelNameListModel::tryRename(const QString &oldName, const QString &newName)
{
    if (oldName == newName) return;

    tryRemoveName(oldName);
    tryAddName(newName);
}
